lib.use(['element', 'table', 'form','tablePlug', 'laydate','element'], function () {
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;
    var laydate=layui.laydate;
    var element=layui.element;
    var probHeadTable;
    var tablePlug = layui.tablePlug //表格插件
    var searchFrm = layui.Form('searchFrm');
    /**
     * 页面加载完成调用方法
     * 初始化方法可以写在这里
     */
    (function () {
     //   common.util.initPage();
    })();
    table.set(common.layui.table.config(tablePlug));
    searchFrm.selectRender();
    laydate.render({elem: '#prodData' ,range: '至'});
    laydate.render({elem: '#checkDate' ,range: '至'});
    // 渲染表格
    probHeadTable = table.render({
         elem: '#probHeadTable'
        , url: common.util.createUrl('/sale/probHead/list')
        //, height: 'full-42'
        , cols: [[
             {type:'checkbox'}
            ,{type: 'numbers', title: '编号' }
            ,{ field: 'id',  hide: true }
            ,{  field: 'entId',  hide: true}
            ,{  field: 'id',  hide: true}
            ,{ title: '预订单编码', field: 'probNo' ,width:180,  event: 'collapse',templet: function(d) {
                    return '<div style="cursor:hand;cursor:pointer;position: relative; padding: 0 10px 0 20px;">' + d.probNo + '<i style="left: 0px;" lay-tips="展开"  style="" class="layui-icon layui-colla-icon layui-icon-right x-admin-pointer "></i></div>'
            }}
            ,{ title: '订单日期', field: 'probDate',width:100 }
            ,{  field: 'storeId',  hide: true}
            ,{ title: '门店名称', field: 'storeName' ,width:150}
            ,{  field: 'customerId',  hide: true}
            ,{ title: '客户编码', field: 'customerCode' }
            ,{ title: '客户名称', field: 'customerName',width:100 }
            //,{ title: '客户联系人', field: 'customerContactName',width:150 }
            ,{ title: '客户电话', field: 'customerContactTel' ,width:120}
            //,{ title: '送货地址', field: 'customerContactAdd' }
            ,{  field: 'guideId',  hide: true}
            ,{ title: '导购员名称', field: 'guideName',width:100 }
            ,{ title: '订单状态', field: 'orderState' ,templet: function (row) { return common.dist.getValue("sale.ProbHead_OrderStateEnum",row.orderState);}}
            ,{  field: 'checkUserId',  hide: true}
            ,{  field: 'checkUserName',  hide: true}
            ,{ title: '审核时间', field: 'checkDate',width:150 }
            ,{ title: '订单类型', field: 'orderType' ,templet: function (row) { return common.dist.getValue("sale.ProbHead_OrderTypeEnum",row.orderType);}}
            ,{ title: '安装日期', field: 'installDate',width:100 }
            ,{ title: '安装标记', field: 'installFlag' ,templet: function (row) { return common.dist.getValue("sale.ProbHead_InstallFlagEnum",row.installFlag);}}
            ,{ title: '量尺标记', field: 'rulerFlag' ,templet: function (row) { return common.dist.getValue("sale.ProbHead_RulerFlagEnum",row.rulerFlag);}}
            ,{  field: 'remark',  hide: true}
            ,{  field: 'createUserId',  hide: true}
            ,{  field: 'createUserName',  hide: true}
            ,{  field: 'createTime',  hide: true}
            ,{  field: 'updateUserId',  hide: true}
            ,{ field: 'updateUserName',width:120 }
            ,{ title: '修改时间', field: 'updateTime' ,width:150}
        ]]
    });

    //监听工具条
    table.on('tool(probHeadTableFilter)',
        function(obj,a,b,c) {
            var data = obj.data;
            if (obj.event === 'collapse') {
                var trObj = layui.$(this).parent('tr'); //当前行
                var accordion = true //开启手风琴，那么在进行折叠操作时，始终只会展现当前展开的表格。
                var content = '<div class="x-admin-table" style="height: 330px;" ></div>' //内容
                //表格行折叠方法
                collapseTable({
                    elem: trObj,
                    accordion: accordion,
                    content: content,
                    success: function(trObjChildren, index) { //成功回调函数
                        //trObjChildren 展开tr层DOM
                        //index 当前层索引
                        trObjChildren.find('div.x-admin-table').attr("id", index);
                        trObjChildren.find('div.x-admin-table').height("350px");
                        var tabHtml='<div class="layui-tab layui-tab-brief" >\n' +
                        '  <ul class="layui-tab-title">\n' +
                        '    <li class="layui-this">订单明细</li>\n' +
                        '    <li>收款单</li>\n' +
                        '    <li>量尺单</li>\n' +
                        '    <li >销售订单</li>\n' +
                        '    <li>发货单</li>\n' +
                        '    <li>安装单</li>\n' +
                        '    <li>完工单</li>\n' +
                        '  </ul>\n' +
                        '  <div class="layui-tab-content" style="height:310px">\n' +
                        '    <div class="layui-tab-item "><iframe  height="310px" src="probLineListTab.html?probId='+data.id+'" frameborder="0" scrolling="yes" class="x-iframe" width="100%" height="100%" style="display:block"></iframe></div>\n' +
                        '    <div class="layui-tab-item"><iframe  height="310px" src="../../fin/receiDetail/receiDetailListTab.html?probId='+data.id+'" frameborder="0" scrolling="yes" class="x-iframe" width="100%" height="100%" style="display:block"></iframe></div>\n' +
                        '    <div class="layui-tab-item"><iframe  height="310px" src="../gaugeSheet/gaugeSheetListTab.html?probId='+data.id+'" frameborder="0" scrolling="yes" class="x-iframe" width="100%" height="100%" style="display:block"></iframe></div>\n' +
                        '    <div class="layui-tab-item"><iframe  height="310px" src="../orderHead/orderHeadListTab.html?probId='+data.id+'" frameborder="0" scrolling="yes" class="x-iframe" width="100%" height="100%" style="display:block"></iframe></div>\n' +
                        '    <div class="layui-tab-item"><iframe  height="310px" src="../deliverHead/deliverHeadListTab.html?probId='+data.id+'" frameborder="0" scrolling="yes" class="x-iframe" width="100%" height="100%" style="display:block"></iframe></div>\n' +
                        '    <div class="layui-tab-item"><iframe  height="310px" src="../installHead/installHeadListTab.html?probId='+data.id+'" frameborder="0" scrolling="yes" class="x-iframe" width="100%" height="100%" style="display:block"></iframe></div>\n' +
                        '    <div class="layui-tab-item"><iframe  height="310px" src="../installFinish/installFinishListTab.html?probId='+data.id+'" frameborder="0" scrolling="yes" class="x-iframe" width="100%" height="100%" style="display:block"></iframe></div>\n' +
                        '  </div>\n' +
                        '</div>'
                        $("#"+index).html(tabHtml);
                        element.render('tab');
                        setTimeout(function(){
                            $("#"+index).find("li.layui-this").click()
                        }, 200);

                    }
                });
            }
        });


    function collapseTable(options) {
        var trObj = options.elem;
        if (!trObj) return;
        var accordion = options.accordion,
            success = options.success,
            content = options.content || '';
        var tableView = trObj.parents('.layui-table-view'); //当前表格视图
        var id = tableView.attr('lay-id'); //当前表格标识
        var index = trObj.data('index'); //当前行索引
        var leftTr = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + index + '"]'); //左侧当前固定行
        var rightTr = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + index + '"]'); //右侧当前固定行
        var colspan = trObj.find('td').length; //获取合并长度
        var trObjChildren = trObj.next(); //展开行Dom
        var indexChildren = id + '-' + index + '-children'; //展开行索引
        var leftTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + indexChildren + '"]'); //左侧展开固定行
        var rightTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + indexChildren + '"]'); //右侧展开固定行
        var lw = leftTr.width() + 15; //左宽
        var rw = rightTr.width() + 15; //右宽
        //不存在就创建展开行
        if (trObjChildren.data('index') != indexChildren) {
            //装载HTML元素
            var tr = '<tr data-index="' + indexChildren + '" style="background-color: #fff"><td colspan="' + colspan + '"><div style="height: auto;padding-left:' + lw + 'px;padding-right:' + rw + 'px" class="layui-table-cell">' + content + '</div></td></tr>';
            trObjChildren = trObj.after(tr).next().hide(); //隐藏展开行
            var fixTr = '<tr data-index="' + indexChildren + '"></tr>';//固定行
            leftTrChildren = leftTr.after(fixTr).next().hide(); //左固定
            rightTrChildren = rightTr.after(fixTr).next().hide(); //右固定
        }
        //展开|折叠箭头图标
        trObj.find('td[lay-event="collapse"] i.layui-colla-icon').toggleClass("layui-icon-right layui-icon-down");
        //显示|隐藏展开行
        trObjChildren.toggle();
        //开启手风琴折叠和折叠箭头
        if (accordion) {
            trObj.siblings().find('td[lay-event="collapse"] i.layui-colla-icon').removeClass("layui-icon-down").addClass("layui-icon-right");
            trObjChildren.siblings('[data-index$="-children"]').hide(); //展开
            rightTrChildren.siblings('[data-index$="-children"]').hide(); //左固定
            leftTrChildren.siblings('[data-index$="-children"]').hide(); //右固定
        }
        success(trObjChildren, indexChildren); //回调函数
        heightChildren = trObjChildren.height(); //展开高度固定
        rightTrChildren.height(heightChildren + 115).toggle(); //左固定
        leftTrChildren.height(heightChildren + 115).toggle(); //右固定
    }
    //监听行单击事件（单击事件为：rowDouble）
    table.on('rowDouble(probHeadTableFilter)', function(obj){
        update(obj)
    });
    $(document).on('click','#del',function(){
        del(table.checkStatus('probHeadTable'))
    });
    $(document).on('click','#check',function(){
        check(table.checkStatus('probHeadTable'))
    });
    $(document).on('click','#add',function(){
        var config = {
            title:"新增预订单",
            content: 'sale/probHead/probHeadForm.html'
        }
        common.util.openWindow(busCommon.windowConfig(config))
    });
    $(document).on('click','#export',function(){
        var params=common.from.serializeObject('#searchFrm');
        params['pages']=probHeadTable.config.page.pages;
        params['limit']=probHeadTable.config.page.limit;
        common.util.exportWindows('/sale/probHead/export',{})
    });
    form.on('submit(searchFilter)', function(data){
        var param = data.field;
        searchTable(param);
        return false;
    });


    /**
     * 查询表格
     * @param params
     */
    function searchTable(params) {
        params=common.from.serializeObject('#searchFrm');
        probHeadTable=table.reload('probHeadTable',{
                where:params,
                page: {curr: 1 }
            }
        )

    }
    /**
     * 修改
     * @param obj
     */
    function update(obj) {
        if(!common.auth.hasPermission("sale:probHead:update")){return;}
        var postData = [];
        if(obj.data.constructor === Array){
            postData=obj.data.map(function (item) {
                return item['id'];
            });
        }else{
            postData=[obj.data.id]
        }
        if(postData.length!=1)return;
        var config = {
            title:"修改预订单",
            content: 'sale/probHead/probHeadForm.html?id=' + postData[0]
        }
        common.util.openWindow(busCommon.windowConfig(config))
    }
    /**
     * 删除
     * @param obj
     */
    function del(obj) {
        if(!common.auth.hasPermission("sale:probHead:delete")){return;}
        var postData = [];
        if(obj.data.constructor === Array){
            postData=obj.data.map(function (item) {
                return item;
            });
        }else{
            postData=[obj.data]
        }

        if(postData.length!=1){common.util.error('请选择一条记录进行操作');return;}
        if(postData[0].orderState!=1){common.util.error('[{0}] 当前订单非未审核状态,,禁止删除'.format(postData[0].probNo));return;}
        common.util.confirm('确认删除!', function(index){
            console.log('Config Del param is', postData);
            common.ajax.get('/sale/probHead/delete/'+postData[0].id,null, function (resp) {
                searchTable();
                layer.close(index);
            })

        });
    }

    /**
     * 审核
     * @param obj
     */
    function check(obj) {
        if(!common.auth.hasPermission("sale:probHead:check")){return;}
        var postData = [];
        if(obj.data.constructor === Array){
            postData=obj.data.map(function (item) {
                return item;
            });
        }else{
            postData=[obj.data]
        }

        if(postData.length!=1){common.util.error('请选择一条记录进行操作');return;}
        if(postData[0].orderState!=1){common.util.error('[{0}] 当前订单非未审核状态,,禁止审核'.format(postData[0].probNo));return;}
        common.util.confirm('确认审核!', function(index){
            console.log('Config Check param is', postData);
            common.ajax.get('/sale/probHead/check/'+postData[0].id, null, function (resp) {
                layer.close(index);
                common.util.success("审核成功");
                searchTable();
            })

        });
    }


    function initProbLine(id) {
        var tableConfig={
            id:"probLineTable",
            elem: '#probLineTable'
            ,height: 'full-288'
            ,toolbar: '#toolbar'
            ,primaryKey: 'id'
            //,where: {orderId:1}
            ,data: []
            ,even: true
            , cols: [[
                {type:'checkbox'}
                ,{type: 'numbers', title: '编号' }
                ,{ field: 'id',  hide: true }
                ,{ title: '商品编码', field: 'goodsCode',}
                ,{ title: '商品名称', field: 'goodsName',}
                ,{ title: '商品型号', field: 'goodsModel',}
                ,{ title: '商品规格', field: 'goodsSpec',}
                ,{ title: '库存数量', field: 'qtyNum',  edit: 'number',must:true}
                ,{ title: '库存单位', field: 'qtyUomName' }
                ,{ title: '辅助数量', field: 'auxNum',  edit: 'number',must:true}
                ,{ title: '辅助单位', field: 'auxUomName' }
                ,{ title: '基本数量', field: 'baseNum'}
                ,{ title: '基本单位', field: 'baseUomName' }
                ,{ title: '商品单价', field: 'goodsPrice',  edit: 'number',must:true}
                ,{ title: '挂牌价', field: 'goodsListPrice',}
                ,{ title: '商品金额', field: 'goodsAmount',}
                ,{ title: '商品折扣', field: 'goodsDiscount',  edit: 'number',must:true}
                ,{ title: '件换算', field: 'converUnit1'}
                ,{ title: '片换算', field: 'converUnit2'}
                ,{ title: '备注', field: 'remark'}
            ]]
            ,done: function (res, curr, count) {
                layer.closeAll('loading');
            }
        };

        //=====================================================从表==========================================================
        table.render(tableConfig);

        common.ajax.get('/sale/probHead/info/'+id, {}, function (resp) {
            common.layui.table.get('probLineTable').load(resp.data.probLineEntityList)
        });
    }


    window.formCallBack=function (params) {
        var contentWindow=$('[data-index^="probHeadTable"]:visible .layui-tab-item.layui-show').find("iframe")[0].contentWindow;
        if(contentWindow&&contentWindow.formCallBack){
            contentWindow.formCallBack(params);
        }
    };

})
